package com.itboye.lottery.retrofit;

import com.itboye.lottery.BuildConfig;

import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static com.itboye.lottery.utils.Utils.getToken;
import static com.itboye.lottery.utils.Utils.getVersion;


public class OkHttpManager {

    private static OkHttpManager m_ins = null;

    public static OkHttpManager getClient() {
        if (m_ins == null) {
            synchronized (OkHttpManager.class) {
                if (m_ins == null) {
                    m_ins = new OkHttpManager();
                }
            }
        }
        return m_ins;
    }

    public OkHttpClient getOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.retryOnConnectionFailure(true);
        builder.connectionPool(new ConnectionPool());
        builder.connectTimeout(50000, TimeUnit.SECONDS);
        builder.readTimeout(50000, TimeUnit.SECONDS);
        builder.writeTimeout(50000, TimeUnit.SECONDS);
        builder.addInterceptor(new LogInterceptor());
//        builder.addInterceptor(interceptor);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            String isDebug = BuildConfig.DEBUG ? "dev" : "dev";
            HttpUrl.Builder builder1 = original.url()
                    .newBuilder()
//                    .setEncodedQueryParameter("env", "debug")//测试环境需传
                    .setEncodedQueryParameter("env", isDebug)//正式环境
                    .setEncodedQueryParameter("token", getToken())
                    .setEncodedQueryParameter("app_version", getVersion())
                    .setEncodedQueryParameter("app_type", "android");
//
            Request request = original.newBuilder().header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")//添加请求头注解//.header("Connection", "close")
                    .method(original.method(), original.body())
                    .url(builder1.build())
                    .build();
//            if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
//                request.header("Connection", "close");
//            }
            return chain.proceed(request);
        });
        return builder.build();
    }


//    Interceptor interceptor = (Interceptor) chain -> {
//        Request request = chain.request();
//        request = request.newBuilder().build();
//        Set<String> param = request.url().queryParameterValue(0);
//        Log.v("request", "responseUrl:" + request.url().url().getHost() + request.url().url().getPath());
//
//        for (String s : param) {
//            Log.v("request", "key:" + s + "  value:" + request.url().queryParameter(s));
//        }
//        return chain.proceed(request);
//    };
}
